import { AxiosRequestConfig } from 'axios';
export const pendingRequests = new Map();
function sortObject(obj: any): any {
  if (obj === null || typeof obj !== 'object' || obj instanceof Date) {
    return obj;
  }
  if (Array.isArray(obj)) {
    return obj.map(sortObject);
  }
  return Object.keys(obj)
    .sort()
    .reduce(
      (acc, key) => {
        acc[key] = sortObject(obj[key]);
        return acc;
      },
      {} as Record<string, any>
    );
}
export function generateRequestKey(config: AxiosRequestConfig) {
  const { url, method, params, data } = config;
  const paramsStr = JSON.stringify(sortObject(params));
  const dataStr = JSON.stringify(sortObject(data));
  return `${method?.toUpperCase()}:${url}?params=${paramsStr}&data=${dataStr}`;
}
export function cancleSameReq(req: AxiosRequestConfig) {
  const key = generateRequestKey(req);
  if (pendingRequests.has(key)) {
    const source = pendingRequests.get(key);
    source.abort(`Duplicate request: ${key}`);
  }
  const controller = new AbortController();
  req.signal = controller.signal; // 绑定 signal
  pendingRequests.set(key, controller);
}

export function setToken(req: AxiosRequestConfig) {
  if (req.headers) {
    req.headers['Authorization'] =
      'Bearer ' + localStorage.getItem('token') || '';
  }
}
